﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Yugi_Gui
{
    class SequenceImage : Image
    {
        DispatcherTimer timer;
        int img_index;
        Action invoker;
        List<ImageSource> data = new List<ImageSource>();
        public SequenceImage()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(70);
            timer.Tick += new EventHandler(timer_Tick);
        }

        public void LoadBuffer(int count,string formater)
        {
            
            ImageSourceConverter convert = new ImageSourceConverter();
            for (int i = 1; i <= count; i++)
            {
                data.Add(new BitmapImage(
                    new Uri( String.Format(formater,i))
                ));
            }
            img_index = 0;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.Source = data[img_index];
            if (img_index == data.Count - 1)
            {
                if (Repeat <= 0)
                {
                    
                    timer.Stop();
                    this.Visibility = Visibility.Hidden;
                    if (invoker != null)
                        invoker();
                }
                else
                {
                    img_index = 0;
                    Repeat--;
                }
            }
            else
                img_index++;
        }

        public void Begin()
        {
            img_index = 0;
            this.Visibility = Visibility.Visible;
            timer.Start();
            
        }
        public void Begin(Action complete)
        {
            this.invoker = complete;
            img_index = 0;
            this.Visibility = Visibility.Visible;
            timer.Start();
        }
        
        public void SetData(List<ImageSource> data)
        {
            this.data = data;
        }

        public int Repeat { get; set; }

        public int TickChange
        {
            get
            {
                return timer.Interval.Milliseconds;
            }
            set
            {
                this.timer.Interval = TimeSpan.FromMilliseconds(value);
            }
        }
        
    }
}
